package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private BpmnInfoServiceImpl bpmnInfoService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ServiceItemServiceImpl serviceItemService;
    @Autowired
    private TaskService taskService;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);

    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public InputStream getProcessImageByAuditId(Long id) {
        //根据id查询审核对象,判断审核对象的状态
        CarPackageAudit audit = this.get(id);
        //流程实例id
        String instanceId = audit.getInstanceId();
        List<String> hingLightedActivities = null;
        //审核中
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            //获取流程实例对象
            //如果处于审核中,需要高亮目前运行节点
            //获取运行的任务
            hingLightedActivities = runtimeService.getActiveActivityIds(instanceId);
        } else {
            //如果是审核通过,审核拒绝.不需要高亮任何节点
            hingLightedActivities = new ArrayList<>();
        }
        //根据bpmnInfoI|d获取bpmnInfo对象,对象中存储流程定义对象
        BpmnInfo bpmnInfo = bpmnInfoService.get(audit.getBpmnInfoId());
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        return generator.generateDiagram(model,hingLightedActivities, Collections.EMPTY_LIST,"宋体","宋体","宋体");
    }

    @Override
    public void cancelApply(Long id) {
        //合理性校验 套餐处于进行中才可撤销
        CarPackageAudit audit = get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            throw new BusinessException("只有处于审核中的记录才能被撤销");
        }
        //服务单项中审核状态设置为初始化
        Long serviceItemId = audit.getServiceItemId();
        serviceItemService.changeAuditStatus(serviceItemId, ServiceItem.SALESTATUS_OFF);
        //删除流程定义实例
        runtimeService.deleteProcessInstance(audit.getInstanceId(),"审核撤销");
        //撤销后状态设置为审核撤销3
        carPackageAuditMapper.chengeStatus(id,CarPackageAudit.STATUS_CANCEL);
    }

    @Override
    public void audit(Long id, Integer auditStatus, String info) {
        // 合理性判断
        CarPackageAudit carPackageAudit = get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("只有审核中状态才能进行审核操作");
        }
        if (!ShiroUtils.getUserId().equals(carPackageAudit.getAuditorId())) {
            throw new BusinessException("只有" + ShiroUtils.getUser().getUserName() + "才能审核该数据");
        }
        // 根据auditStatus判断是审核通过还是审核拒绝,需要在info中存储审核意见
        String userName = ShiroUtils.getUser().getUserName();
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            // 审核通过
            info = "[" + userName + "]:审核通过,意见" + info;
        } else {
            // 审核拒绝
            info = "[" + userName + "]:审核拒绝,意见" + info;
        }
        carPackageAudit.setInfo(carPackageAudit.getInfo() + "</br>" + info);
        // 让 Activiti 流程往后流转
        Task currentTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        // 完成任务前设置流程变量 auditStatus
        taskService.setVariable(currentTask.getId(), "auditStatus", auditStatus);
        // 执行任务
        taskService.complete(currentTask.getId());
        // 设置最后审核时间
        carPackageAudit.setAuditTime(new Date());
        // 根据审核通过还是拒绝做不同的逻辑任务
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            // 审核通过
            // 查询是否有下一个节点
            Task nextTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            if (nextTask == null) {
                // 流程执行完
                // 审核人为null
                carPackageAudit.setAuditorId(null);
                // 把审核对象的状态修改为审核通过
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
                // 把服务单项状态修改为审核通过
                serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(), ServiceItem.AUDITSTATUS_APPROVED);
            } else {
                // 有下个节点
                // 修改审核对象的的审核人为下个节点的审核人
                carPackageAudit.setAuditorId(Long.valueOf(nextTask.getAssignee()));
                System.out.println(nextTask.getAssignee());
            }
        } else {
            // 审核拒绝
            // 审核人为null
            carPackageAudit.setAuditorId(null);
            // 把服务单项状态修改为重新调整
            serviceItemService.changeAuditStatus(id, ServiceItem.AUDITSTATUS_REPLY);
        }
        // 跟新审核对象
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }
}
